import pandas, duckdb
from config import ini_op
from openpyxl import  load_workbook
import os
from utils.path_utils import get_project_root
from database.duckdb.duckdb_base import get_connection



# timenow = str(strftime("%Y%m%d%H%M%S"))
def run(zbid, kjnd, timenow):
  conn = get_connection()

  conn.execute("""
               delete from T_API_KMNC where kjnd = ? and LEDGER = ? and ACCTITLECODE in (select Kmdm from GL_Kmye group by Kmdm);
               """, [kjnd, zbid])
  conn.execute("""
    insert into T_API_KMNC (LEDGER, ACCTITLECODE, BALANCEDIR, BEGINBALANCEAMT, CURCUMDRAMT, CURCUMCRAMT, ENDBALANCEAMT, esun_api_update, kjnd)
              select
                '"""+zbid+"""',
                Kmdm,
                CASE 
                    WHEN Kmncj > Kmjcd THEN 1
                    WHEN Kmncj < Kmjcd THEN 2
                    ELSE 0
                end,
                CAST(ABS(Kmncj - Kmjcd) AS DECIMAL(18, 2)),
                CAST(0 AS DECIMAL(18, 2)),
                CAST(0 AS DECIMAL(18, 2)),
                CAST(0 AS DECIMAL(18, 2)),
                '"""+timenow+"""',
                '"""+kjnd+"""'
               from GL_Kmye;
    delete from T_API_KMNC where ACCTITLECODE = '合计';
  """)

  conn.close()
